#region Copyright
// Copyright (c) 2010, Kazi Manzur Rashid <kazimanzurrashid@gmail.com>.
// This source is subject to the Microsoft Public License. 
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. 
// All other rights reserved.
#endregion

namespace LiveWriter.Plugins.Snippet
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;

    internal static class SupportedSettings
    {
        private static readonly string pluginPath = Path.Combine(RuntimeInfo.PluginPath, "Snippet");

        public static readonly IList<Pair> Languages = LoadLanguages();
        public static readonly IList<Pair> Styles = LoadStyles();

        private static IList<Pair> LoadLanguages()
        {
            string languageFile = Path.Combine(pluginPath, "languages.xml");

            return LoadFromFileOrResource(languageFile, "LiveWriter.Plugins.Snippet.languages.xml");
        }

        private static IList<Pair> LoadStyles()
        {
            string styleFile = Path.Combine(pluginPath, "styles.xml");

            return LoadFromFileOrResource(styleFile, "LiveWriter.Plugins.Snippet.styles.xml");
        }

        private static IList<Pair> LoadFromFileOrResource(string filePath, string resourceName)
        {
            XDocument doc;

            if (File.Exists(filePath))
            {
                doc = XDocument.Load(filePath);
            }
            else
            {
                Stream resource = typeof(SupportedSettings).Assembly.GetManifestResourceStream(resourceName);
                doc = XDocument.Load(XmlReader.Create(resource));
            }

            IList<Pair> languages = doc.Root
                                       .Elements("item")
                                       .Select(x => new Pair { Key = x.Attribute("internalName").Value, Value = x.Attribute("displayName").Value })
                                       .OrderBy(p => p.Key)
                                       .ToList();

            return languages;
        }
    }
}